
package com.dji.common.utils;

import java.io.File;
import java.lang.reflect.Field;

public class ClassUtils {
	public static final String CLASS_EXTENSION = ".class";
	public static final String JAVA_EXTENSION = ".java";

	public static void setFieldValue(Object souce, String fieldName, Object value) throws Exception {
		Class<? extends Object> objectClass = souce.getClass();
		Field field = objectClass.getDeclaredField(fieldName);
		field.setAccessible(true);
		field.set(souce, value);
	}

	public static Object newInstance(File classFile) throws Exception {
		return Class.forName(getPackageInfo(classFile).replace(File.separator, ".")).newInstance();
	}

	public static Object newInstance(String classInfo) throws Exception {
		return Class.forName(classInfo).newInstance();
	}

	public static Class<?> getClass(File classFile) throws Exception {
		return Class.forName(getPackageInfo(classFile).replace(File.separator, "."), false,
				ClassUtils.class.getClassLoader());
	}

	public static String getPackageInfo(File classFile) throws Exception {
		String filePath = classFile.getAbsolutePath();
		if (filePath.endsWith(CLASS_EXTENSION)) {
			filePath = filePath.substring(0, filePath.length() - 6);
			filePath = filePath.substring(filePath.indexOf("\\bin\\") + 5);
		} else if (filePath.endsWith(JAVA_EXTENSION)) {
			filePath = filePath.substring(0, filePath.length() - 5);
			filePath = filePath.substring(filePath.indexOf("\\src\\") + 5);
		}
		return filePath.replace(File.separator, ".");
	}
}
